package com.liy.jiagou.product.resources;

import com.liy.jiagou.common.api.entity.ResultVo;
import com.liy.jiagou.product.entity.ProductEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;


import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * Product 资源服务类
 *
 */
@RestController
public class ProductController {

    private Logger logger = LoggerFactory.getLogger(ProductController.class);


    /**
     *  随便一个接口服, 如果用户没有  登录认证的信息 -> token
     *  那么是无权进行访问的
     */
    @GetMapping("/index")
    ResultVo index() {
        return ResultVo.ok("Welcome to Product Server ....","Access Product Resources Server is OK");
    }

    @GetMapping("/")
    ResultVo home() {
        return ResultVo.ok("Welcome to Product Server ....","Access Product Resources Server is OK");
    }


    /**
     * 查询商品接口
     *
     */
    @PreAuthorize("hasAuthority('product.query')")
    @GetMapping("/query/product")
    ResultVo getProduct(@RequestParam("productId") String  productId) {
        logger.info("------------------- ProductController-------------- getProduct() "    );
        ProductEntity productEntity = new ProductEntity(productId, "query-product");
        return ResultVo.ok(productEntity,"/query/product invoke success");
    }


    @PreAuthorize("hasAuthority('product.add')")
    @PostMapping("/add/product")
    ResultVo addProduct(ProductEntity product) {
        logger.info("------------------- ProductController-------------- addProduct() "    );
        return ResultVo.ok(product,"/add/product invoke success");
    }


    /**
     *  测试 当前用户的 权限信息
     *
     */
    @RequestMapping("/info/authentication")
    public Authentication info(Authentication authentication) {
        return authentication;
    }


    /**
     *  测试 PreAuthorize 权限拦截
     *
     */
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @RequestMapping("/test/PreAuthorize")
    public ProductEntity addProduct() {

        // 安全上下文
        SecurityContext securityContext = SecurityContextHolder.getContext();
        // authentication 认证信息对象
        Authentication authentication = securityContext.getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        Object principal = authentication.getPrincipal();
        String username;
        if (principal instanceof UserDetails) {
            username = ((UserDetails)principal).getUsername();
        } else {
            username = principal.toString();
        }

        return  new ProductEntity(username, "10001");
    }

}
